//
//  DeveloperController.swift
//  Social
//
//  Created by Hayden on 2019/7/12.
//  Copyright © 2019 shengsheng. All rights reserved.
//

import UIKit
import WebKit
import Kingfisher
import SwiftMessages
import SystemConfiguration.CaptiveNetwork

class DeveloperController: ViewController<DeveloperView> {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func commit(_ sender: Any) {
        let mode = Env(rawValue: container.state.rawValue) ?? .main
        changeMode(mode)
    }
    
    @IBAction func report(_ sender: Any) {
//        LoggerUploader.upload(with: UIDevice.current.name, data: Logger.content) { (success) in
//            Toast.show(top: "上传" + (success ? "成功" : "失败"))
//        }
    }
    
    @IBAction func copyLog(_ sender: Any) {
//        UIPasteboard.general.string = String(data: Logger.content ?? Data(), encoding: .utf8) ?? ""
//        Toast.show(top: "已拷贝到剪切板")
    }
    
    private func clearCache(completion: @escaping () -> Void) {
        DispatchQueue.main.async {
            let group = DispatchGroup()
            
            // 清理UD缓存
            let all = UserDefaults.standard.dictionaryRepresentation()
            all.forEach { UserDefaults.standard.removeObject(forKey: $0.key) }
            
            // 清理Web缓存
            group.enter()
            WKWebsiteDataStore.default().removeData(
                ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(),
                modifiedSince: Date(timeIntervalSince1970: 0)
            ) {
                group.leave()
                print("清理Web缓存完成")
            }
            
            // 清理图片缓存
            group.enter()
            KingfisherManager.shared.cache.clearDiskCache {
                group.leave()
                print("清理图片缓存完成")
            }
            
            // 清理其他缓存
            group.enter()
            DispatchQueue.global().async {
                Cache.shared.clear()
                Cache(.caches, "Share").clear()
                group.leave()
                print("清理其他缓存完成")
            }
            
            group.notify(queue: .main, execute: completion)
        }
    }
    
    private func changeMode(_ mode: Env) {
        guard Env.current != mode else {
            showWarning("当前环境已为\(mode.name)")
            close()
            return
        }
//        guard !Account.isLogin else {
//            // 退出当前登录用户
//            Account.logout() { self.changeMode(mode) }
//            return
//        }
//
        clearCache(completion: {
            Env.current = mode
            self.prompt("已切换至\(mode.name)环境 😏")
        })
    }
    
    private func prompt(_ msg: String) {
        
        SwiftMessages.hideAll()
        
        let view = MessageView.viewFromNib(layout: .centeredView)
        view.configureContent(body: msg)
        view.button?.setTitle("立即关闭", for: .normal)
        view.buttonTapHandler = { sender in exit(0) }
        view.titleLabel?.isHidden = true
        view.configureTheme(.success)
        view.configureDropShadow()
        
        var config = SwiftMessages.defaultConfig
        config.presentationStyle = .center
        config.interactiveHide = false
        config.duration = .forever
        config.preferredStatusBarStyle = .lightContent
        config.dimMode = .blur(style: .dark, alpha: 1, interactive: false)
        SwiftMessages.show(config: config, view: view)
    }
    
    private func showWarning(_ msg: String) {
        let view = MessageView.viewFromNib(layout: .cardView)
        view.configureContent(body: msg)
        view.configureTheme(.warning)
        view.button?.isHidden = true
        view.titleLabel?.isHidden = true
        view.configureDropShadow()
        
        var config = SwiftMessages.defaultConfig
        config.duration = .seconds(seconds: 4)
        SwiftMessages.show(config: config, view: view)
    }
}

extension DeveloperController {
    
//    static func instance() -> Self {
//        return StoryBoard.alert.instance()
//    }
}
